#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/10/27 13:08
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : ser_email_config.py
# @Software: PyCharm
# @Desc    :

from rest_framework import serializers

from semail.models import EmailConfig


class EmailConfigSerializer(serializers.ModelSerializer):
    """
    EmailConfig序列化器：
    1. 授权码/密码仅写入，返回时隐藏
    2. 默认配置唯一性校验
    3. SMTP端口合理性校验
    """
    # 敏感字段：仅创建/更新时接收，返回时不展示
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)
    update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)
    # email_password = serializers.CharField(write_only=True, required=True)

    class Meta:
        model = EmailConfig
        fields = [
            "id", "name", "email_host", "email_port", "email_user",
            "use_ssl", "is_default", "sort_num", "is_active",
            "create_time", "update_time", "email_password"
        ]
        read_only_fields = ["create_time", "update_time"]

    def validate_email_port(self, value):
        """校验SMTP端口：范围在1-65535之间"""
        if not (1 <= value <= 65535):
            raise serializers.ValidationError("SMTP端口无效，请输入1-65535之间的数字")
        return value

    # def validate_is_default(self, value):
    #     """校验默认配置：系统只能有一个默认配置"""
    #     if not value:
    #         return value  # 非默认配置，直接通过

        # # 筛选有效（未删除+非压测）的配置
        # queryset = EmailConfig.objects.filter(is_delete=0, pt_flag=0)
        # # 新增场景：检查是否已有默认配置
        # if self.instance is None:
        #     if queryset.filter(is_default=True).exists():
        #         raise serializers.ValidationError("系统已存在默认邮箱配置，无法重复设置")
        # # 更新场景：排除当前配置后，检查是否已有默认配置
        # else:
        #     if queryset.exclude(id=self.instance.id).filter(is_default=True).exists():
        #         raise serializers.ValidationError("系统已存在默认邮箱配置，无法重复设置")
        # return value

    def validate_name(self, value):
        """校验配置名称：非空且唯一（有效配置内）"""
        value = value.strip()
        if not value:
            raise serializers.ValidationError("配置名称不能为空")

        queryset = EmailConfig.objects.filter(is_delete=0, pt_flag=0)
        # 新增：名称不能重复
        if self.instance is None:
            if queryset.filter(name=value).exists():
                raise serializers.ValidationError(f"配置名称「{value}」已存在，请更换")
        # 更新：排除当前配置后名称不能重复
        else:
            if queryset.exclude(id=self.instance.id).filter(name=value).exists():
                raise serializers.ValidationError(f"配置名称「{value}」已存在，请更换")
        return value
